<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.gxgyl.com All rights reserved.

// +----------------------------------------------------------------------
// | Author: Liuyu
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\shiyao;

use app\common\model\shiyao\ProjectCenter as ProjectCenterModel;
use app\common\service\store\User as UserService;
use think\facade\Db;

/**
 * 申办方模型
 * Class StoreUser
 * @package app\store\model
 */
class ProjectCenter extends ProjectCenterModel {

	public function getListAll($param = []) {
		// 查询模型
		$query = $this->getNewQuery();

		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['search' => '', 'betweenTime' => [], 'projectId' => '']);
		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}
		!empty($params['projectId']) && $filter[] = ['p.project_id', '=', $params['projectId']];

		// 查询列表记录
		$list = $query->alias('p')->with(['project.company', 'pi', 'crc', 'pms.user'])
			->field('p.*')
			->join('shiyao_project pr', 'pr.project_id=p.project_id')
			->join('shiyao_company c', 'c.company_id=pr.company_id')
			->where('p.is_delete', '=', '0')
			->where($filter)
			->order(['p.center_code' => 'asc'])
			->select()->toArray();

		foreach ($list as $key => $value) {
			$list[$key]['center_code']=$value['center_code'].'/'.$value['center_name'];
			$room = [];
			if ($value['pi']) {
				foreach ($value['pi'] as $k => $pi) {
					$room[] = $pi['name'] . '(' . $pi['room'] . ')';
				}
				$list[$key]['room'] = implode(',', $room);
			} else {
				$list[$key]['room'] = '';
			}
			$crc = [];
			if ($value['crc']) {
				foreach ($value['crc'] as $kc => $crcd) {
					$crc[] = $crcd['name'];
				}
				$list[$key]['crc'] = implode(',', $crc);
			} else {
				$list[$key]['crc'] = '';
			}
			$pms = [];
			if (!empty($value['pms'])) {
				foreach ($value['pms'] as $kp => $pmsd) {
					$pms[] = $pmsd['user']['nick_name'];
				}

				$list[$key]['pms'] = implode(',', $pms);
			} else {
				$list[$key]['pms'] = '';
			}

		}

		return $list;
	}

	/**
	 * 获取用户列表
	 * @param array $param
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getList($param = []) {
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['search' => '', 'betweenTime' => []]);
		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}

		// 关键词搜索
		!empty($params['search']) && $query->where('p.center_name', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')
		//->join('shiyao_company c','c.company_id=p.company_id')
			->where('p.is_delete', '=', '0')
			->where($filter)
			->order(['p.create_time' => 'desc'])
			->paginate(15);

		return $list;
	}

	/**
	 * 获取项目-中心
	 * @param array $param
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getListCenter($param = []) {
		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['projectId' => '', 'centerId' => '', 'companyId' => '', 'search' => '', 'betweenTime' => []]);
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}
		!empty($store_user['company_id']) && $query->where('pr.company_id', '=', $store_user['company_id']);

		!empty($params['projectId']) && $query->where('p.project_id', '=', $params['projectId']);

		$project = '';

		$params['projectId'] > 0 && $project = Db::name('shiyao_project')->where('project_id', $params['projectId'])->find();
		//根据角色筛选
		$role = Db::name('store_user_role')->where('role_id', 'in', [10006, 10009])
			->where('store_user_id', $store_user['store_user_id'])->find();
		$filter = [];
		if ($role || $store_user['store_user_id'] == 10001) {

		} else {

			$user = Db::name('user')->where('mobile', $store_user['user_name'])->find();

			//审批人员
			$userId = $user['user_id'];
			$centerIds = Db::name('shiyao_project_center_pm')
				->where('pm_id', $userId)
				->where('project_id', $params['projectId'])
				->group('center_id')->select()->toArray();
			$centerIds = array_column($centerIds, 'center_id');

			//自己添加的项目
			$pmcenter = Db::name('shiyao_project_center')->where('project_id', $params['projectId'])->where('pm_id', $userId)->field('id')->group('center_id')->select()->toArray();
			$centerIds2 = array_column($pmcenter, 'id');
			$newcenterIds = array_merge($centerIds, $centerIds2);

			if ($newcenterIds) {

				//print_r($newcenterIds);
				$query->where('p.id', 'in', $newcenterIds);
			} else {

				$query->where('p.id', '=', -1); //没有权限，设置空
				if ($project && $project['is_share'] == 0) {

					//是否信息共享

					if ($user) {
						$query->where('p.pm_id|p.pm_id_xiezhu', '=', $user['user_id']);
					}
				}

			}

		}

		!empty($params['centerId']) && $query->where('p.center_id', '=', $params['centerId']);

		// 关键词搜索
		!empty($params['search']) && $query->where('pr.project_name|c.company_name|pr.project_code|p.center_code', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')->with(['project.company', 'pi', 'crc', 'pms.user'])
			->field('p.*')
			->join('shiyao_project pr', 'pr.project_id=p.project_id')
			->join('shiyao_company c', 'c.company_id=pr.company_id')
			->where('p.is_delete', '=', '0')
			->where($filter)
			->order(['p.center_code' => 'asc'])
			->paginate(15)->each(function ($item, $key) {
			$crc = array_column($item['crc']->toArray(), 'name');
			$item['crc_label'] = implode(',', $crc);
			$pm = Db::name('user')->where('user_id', $item['pm_id'])->find();
			$item['pm']= $pm;
			//$xiezhu = Db::name('user')->where('user_id', $item['pm_id_xiezhu'])->value('nick_name');
			//$item['pm'] = $item['pm'] != null ? $item['pm'] : $xiezhu;
			$item['testee_count'] = Db::name('shiyao_project_center_testee')
				->where('center_id', $item['id'])->count();
			//pm待审核
			$item['buzhu_count'] = Db::name('shiyao_project_pay_log')
				->where('center_id', $item['id'])
				->where('pm_status', '=', 0)
				->where('pi_status', '=', 1)
				->where('status', '=', 10)
				->count();
			$pms = array_column($item['pms']->toArray(), 'pm_id');

			//是否具有审批权限
			//$item['is_can'] = in_array($item['pm_id'], $pms) ? 1 : 0;

			return $item;
		});

		return $list;
	}
	/**
	 * 获取项目-按用户-导出
	 * @param array $param
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getListUserAll($param = []) {

		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['userId' => '', 'search' => '', 'betweenTime' => []]);

		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}
		$user = Db::name('user')->where('user_id', $params['userId'])->find();

		// 关键词搜索
		!empty($params['search']) && $query->where('pr.project_name|c.company_name|pr.project_code|center.center_name', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')
			->field('p.*,c.company_name,center.center_name,center.center_code,pr.project_code,pr.project_name')
			->join('shiyao_project pr', 'pr.project_id=p.project_id')
			->join('shiyao_company c', 'c.company_id=pr.company_id')
			->join('shiyao_project_center center', 'center.id=p.center_id')
			->where('p.pm_id', '=', $params['userId'])
			->where('p.is_delete', '=', '0')
			->where($filter)
			->order(['p.create_time' => 'desc'])
			->select()->toArray();
		foreach ($list as $key => $item) {

			$list[$key]['pm'] = Db::name('user')->where('user_id', $item['pm_id'])->value('nick_name');
			$list[$key]['testee_count'] = Db::name('shiyao_project_center_testee')
				->where('center_id', $item['id'])->count();
			$list[$key]['buzhu_count'] = Db::name('shiyao_project_pay_log')
				->where('center_id', $item['id'])->count();
		}

		return $list;
	}
	/**
	 * 获取项目-按用户
	 * @param array $param
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getListUser($param = []) {

		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['userId' => '', 'search' => '', 'betweenTime' => []]);

		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}

		// 关键词搜索
		!empty($params['search']) && $query->where('pr.project_name|c.company_name|pr.project_code|p.center_name', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')
			->field('p.*,c.company_name,center.center_name,center.center_code,pr.project_code,pr.project_name')
			->join('shiyao_project pr', 'pr.project_id=p.project_id')
			->join('shiyao_company c', 'c.company_id=pr.company_id')
			->join('shiyao_project_center center', 'center.id=p.center_id')
			->where('p.pm_id', '=', $params['userId'])
			->where('p.is_delete', '=', '0')
			->where($filter)
			->order(['p.create_time' => 'desc'])
			->paginate(15)->each(function ($item, $key) {

			$item['pms'] = Db::name('shiyao_project_center_pm')->alias('pm')
				->join('user', 'user.user_id=pm.pm_id')
				->where('pm.center_id', $item['center_id'])
				->field('user.*')->select()->toArray();

			$item['pi'] = Db::name('shiyao_project_center_pi')->alias('pi')
				->join('user', 'user.user_id=pi.user_id')
				->where('pi.center_id', $item['center_id'])
				->field('user.nick_name,user.mobile,pi.*')->select()->toArray();
			$item['crc'] = Db::name('shiyao_project_center_crc')->alias('crc')
				->join('user', 'user.user_id=crc.user_id')
				->where('crc.center_id', $item['center_id'])
				->field('user.nick_name,user.mobile,crc.*')->select()->toArray();

			$item['pm'] = Db::name('user')->where('user_id', $item['pm_id'])->find();

			$item['testee_count'] = Db::name('shiyao_project_center_testee')
				->where('center_id', $item['id'])->count();
			$item['buzhu_count'] = Db::name('shiyao_project_pay_log')
				->where('center_id', $item['id'])->count();
			return $item;
		});

		return $list;
	}

	/**
	 * 新增记录
	 * @param array $data
	 * @return bool
	 */
	public function add(array $data) {
		// 当前用户信息
		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];
		// 添加
		return $this->transaction(function () use ($store_user, $data) {

			$center = Db::name('shiyao_center')->where('center_id', $data['center_id'])->find();

			$data['center_name'] = $center['center_name'];
			$data['center_code'] = trim($data['center_code']) . ' ';
			$data['store_id'] = self::$storeId;

			//查询pm是否协助
			$user_id = Db::name('user')->where('mobile', $store_user['user_name'])->value('user_id');
			$project_pm = Db::name('shiyao_project_pm')->where('project_id', $data['project_id'])
				->where('pm_id', $user_id)->find();
			if ($project_pm) {
				$data['pm_id_xiezhu'] = $project_pm['pm_id'];
			}

			$this->save($data);

			// 新增PI

			Pi::increased((int) $this['id'], $data['project_id'], $data['piList']); //2

			//新增CRC
			Crc::increased((int) $this['id'], $data['project_id'], $data['crcList']); //1

			if (isset($data['pm_ids']) && !empty($data['pm_ids'])) {
				//帮助pm添加中心
				foreach ($data['pm_ids'] as $key => $pm) {

					$insertData['project_id'] = $data['project_id'];
					$insertData['center_id'] = $this['id'];

					$insertData['pm_id'] = $pm['value'];
					$insertData['create_time'] = time();
					$insertData['store_id'] = self::$storeId;
					Db::name('shiyao_project_center_pm')->insert($insertData);

				}

			}

			return true;
		});
	}

	/**
	 * 关闭中心
	 * @param array $goodsIds 商品id集
	 * @param bool $state 为true表示上架
	 * @return bool|false
	 */
	public function setStatus(array $goodsIds, bool $state): bool {

		// 批量更新记录
		//  return static::updateBase(['status' => $state ? 1 : 2], [['goods_id', 'in', $goodsIds]]);
		return static::updateBase(['status' => 2], [['id', 'in', $goodsIds]]);
	}
	/**
	 * 更新记录
	 * @param array $data
	 * @return bool
	 */
	public function edit(array $data) {

		// 添加
		return $this->transaction(function () use ($data) {

			$center = Db::name('shiyao_center')->where('center_id', $data['center_id'])->find();

			$d_data['center_id'] = $center['center_id'];
			$d_data['center_name'] = $center['center_name'];
			$d_data['center_code'] = trim($data['center_code']) . ' ';
			$d_data['pm_id'] = $data['pm_id'];

			$d_data['address'] = $data['address'];
			///print_r($d_data);
			$this->save($d_data);

			Db::name('shiyao_project_center_pm')->where('center_id', $this['id'])->delete();

			if (isset($data['pm_ids']) && !empty($data['pm_ids'])) {

				//帮助pm添加中心
				foreach ($data['pm_ids'] as $key => $pm) {

					$insertData['project_id'] = $data['project_id'];
					$insertData['center_id'] = $this['id'];

					$insertData['pm_id'] = $pm['value'];
					$insertData['create_time'] = time();
					$insertData['store_id'] = self::$storeId;
					Db::name('shiyao_project_center_pm')->insert($insertData);

				}

			}
			// 新增PI
			//$Pi = new PiModel;

			Pi::increased((int) $this['id'], $data['project_id'], $data['piList']);

			//新增CRC
			Crc::increased((int) $this['id'], $data['project_id'], $data['crcList']);

			return true;
		});
	}

	public function audit(array $data) {

		$this->transaction(function () use ($data) {
			// 更新记录
			$this->save($data);

		});
		return true;
	}

	/**
	 * 软删除
	 * @return false|int
	 */
	public function setDelete(array $centerIds) {

		foreach ($centerIds as $centerId) {
			$log = Db::name('shiyao_project_pay_log')->where('center_id', $centerId)->find();
			if ($log) {

				$this->error = '当前中心有补助记录，不允许删除';
				return false;
			}

		}

		Db::name('shiyao_project_center')->delete($centerIds);
		// 批量更新记录
		return true;

	}
	public static function detail(int $id) {

		$detail = self::get(['id' => $id], ['pi', 'crc']);

		return $detail;
	}

}
